import { Injectable } from '@nestjs/common';
import { FileStorageService } from '../shared/file-storage.service';
import { CreateFamilyDto, FamilyPreferenceDto } from './dto/family.dto';

@Injectable()
export class FamilyService {
  private readonly FAMILIES_FILE = 'data/families.json';

  constructor(private readonly fileStorage: FileStorageService) {}

  async createFamily(createFamilyDto: CreateFamilyDto) {
    const { families } = await this.fileStorage.readJsonFile(this.FAMILIES_FILE);
    const newFamily = {
      id: Date.now().toString(),
      ...createFamilyDto,
      createdAt: new Date().toISOString(),
    };
    
    families.push(newFamily);
    await this.fileStorage.writeJsonFile(this.FAMILIES_FILE, { families });
    return newFamily;
  }

  async getFamilyById(id: string) {
    const { families } = await this.fileStorage.readJsonFile(this.FAMILIES_FILE);
    return families.find(family => family.id === id);
  }

  async updateFamily(id: string, updateFamilyDto: CreateFamilyDto) {
    const { families } = await this.fileStorage.readJsonFile(this.FAMILIES_FILE);
    const familyIndex = families.findIndex(family => family.id === id);
    
    if (familyIndex === -1) {
      throw new Error('家庭不存在');
    }

    // 更新家庭基本信息,保留原有的创建时间和偏好设置
    const updatedFamily = {
      ...families[familyIndex],
      ...updateFamilyDto,
      id, // 保持原有ID
      createdAt: families[familyIndex].createdAt, // 保持原有创建时间
    };

    families[familyIndex] = updatedFamily;
    await this.fileStorage.writeJsonFile(this.FAMILIES_FILE, { families });
    return updatedFamily;
  }
}